package com.sitech.ibnms.util.charts.fusion.pie;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.sitech.ibnms.util.charts.domain.HIS_DATA_DOMAIN;
import com.sitech.ibnms.util.charts.fusion.FusionChartCommon;

/**
 * @author Mirror_Jean
 *
 * @Date :Jan 10, 2011
 * @Time :3:37:25 PM
 * @Vesion :FusionPieChart
 */
public class FusionPieChart {

	public String getPieChart(FusionPieChartParameter parameter,
			HashMap<String,String[]> rateData) {
		
		return  FusionChartCommon.getScript(parameter).replaceAll("######", 
				this.setPieChartParameter(parameter, rateData).toString());
	}
	
	public String setPieChartParameter(FusionPieChartParameter parameter,
			HashMap<String,String[]> rateData) {
		Document document = DocumentHelper.createDocument();
		try {
			Element chartHead = document.addElement("chart");
			String headAttribute[] = FusionPieChartParamName.paramName;
			String headAttributeValue[] = FusionPieChartParameter.getParamVaule(parameter,headAttribute);
			int idx = 0;
			for (String name : headAttribute) {
				chartHead.addAttribute(name, headAttributeValue[idx]);
				idx++;
			}
			setChildParam(chartHead, "set", rateData);
		} catch (Exception ex) {
			System.out.println("add root chart has exception ,method : setLineChartParameter();");
			ex.printStackTrace();
		}
		return formatXMLData(document);
	}
	
	private void setChildParam(Element parent, String childName,
			HashMap<String,String[]> rateData) {
		try {
			int i = 0;
			if (rateData != null){
				Set<String> key = rateData.keySet();
				Iterator<String> it = key.iterator();
				while (it.hasNext()) {
					Element chartNode = parent.addElement(childName);
					String name = it.next();
					String value = rateData.get(name)[0];
					String color = rateData.get(name)[1];
					//chartNode.addAttribute("label", name);
					chartNode.addAttribute("value", value);
					chartNode.addAttribute("color", color);
					if(name != null && !name.equals(""))
					chartNode.addAttribute("toolText", "("+name+":"+value+")");
				}
			}
		} catch (Exception ex) {
			System.out.println("add child chart node has exception ,method : setChildParam();");
			ex.printStackTrace();
		}
	}
	
	private String formatXMLData(Document document) {
		String xml[] = document.asXML().split("\n");
		System.out.println("xml size : " + xml.length);
		return xml[1].replace("\"", "\'");
	}
}
